import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useFlinkEnvStore = defineStore('flinkEnv', () => {
  // 状态
  const flinkEnvironments = ref([])
  const loading = ref(false)
  
  // 获取Flink环境配置列表
  const fetchFlinkEnvironments = async () => {
    try {
      loading.value = true
      const response = await api.get('/settings?service_type=flink')
      
      if (response.data.success && response.data.data && response.data.data.flink) {
        // 将配置转换为选项格式
        const environments = []
        for (const [configName, config] of Object.entries(response.data.data.flink)) {
          // 构建完整的URL
          const protocol = config.protocol || 'http'
          const host = config.host || ''
          const port = config.port ? `:${config.port}` : ''
          const path = config.path || ''
          const fullUrl = `${protocol}://${host}${port}${path}`
          
          const environment = {
            label: configName,
            value: fullUrl,
            config: config,
            description: config.description || `${configName}环境`
          }
          
          environments.push(environment)
        }
        
        // 按sort_order排序
        environments.sort((a, b) => (a.config.sort_order || 0) - (b.config.sort_order || 0))
        
        flinkEnvironments.value = environments
      } else {
        flinkEnvironments.value = []
      }
      
      return flinkEnvironments.value
    } catch (error) {
      storeLogger.error('获取Flink环境配置失败:', error)
      ElMessage.error('获取Flink环境配置失败')
      flinkEnvironments.value = []
      return []
    } finally {
      loading.value = false
    }
  }
  
  // 根据URL获取环境名称
  const getEnvironmentNameByUrl = (url) => {
    if (!url) return '默认环境'
    
    const env = flinkEnvironments.value.find(e => e.value === url)
    return env ? env.label : '自定义环境'
  }
  
  // 根据环境名称获取URL
  const getUrlByEnvironmentName = (name) => {
    if (!name) return null
    
    const env = flinkEnvironments.value.find(e => e.label === name)
    return env ? env.value : null
  }
  
  // 获取环境选项（用于下拉框）
  const getEnvironmentOptions = () => {
    return flinkEnvironments.value.map(env => ({
      label: env.label,
      value: env.value,
      description: env.description,
      host: env.config.host,
      port: env.config.port,
      protocol: env.config.protocol || 'http'
    }))
  }
  
  return {
    // 状态
    flinkEnvironments,
    loading,
    
    // 方法
    fetchFlinkEnvironments,
    getEnvironmentNameByUrl,
    getUrlByEnvironmentName,
    getEnvironmentOptions
  }
})
